package grabbing.ticket.common.util.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * redis 抢票
 *
 * @author lcf
 */
@Component
public class RedisTicketUtils{
    private static String key = "ticket";

    @Autowired
    protected StringRedisTemplate redisTemplate;
    @Autowired
    private RedisLockUtils lockUtils;

    /**
     * 缓存
     */
    public void cache(Integer v) {
        redisTemplate.opsForValue().set(key, v.toString());
    }

    /**
     * 是否存在
     */
    public boolean hasKey() {
        return Optional.ofNullable(redisTemplate.hasKey(key)).orElse(false);
    }

    /**
     * 获取
     */
    public Integer get() {
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(value)) {
            return 0;
        }

        return Integer.parseInt(value);
    }

    /**
     * 删除
     */
    public void del() {
        redisTemplate.delete(key);
    }

    /**
     * 递增
     */
    public void increment(int num) {
        redisTemplate.boundValueOps(key).increment(num);
    }

    /**
     * 递减
     */
    public boolean decrement(long num) {
        if (get() <= 0) {
            return false;
        }

        if (lockUtils.getLock(5)) {
            if (get() - num < 0) {
                return false;
            }

            redisTemplate.boundValueOps(key).decrement(num);
            lockUtils.unLock();
            return true;
        }

        return false;
    }
}
